package com.imooc.files.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.imooc.files.resource.FileResource;
import com.imooc.files.service.UploaderService;
import com.imooc.utils.extend.AliyunResource;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class UploaderServiceImpl implements UploaderService {

    @Autowired
    public FastFileStorageClient fastFileStorageClient;

    @Autowired
    public FileResource fileResource;

    @Autowired
    public AliyunResource aliyunResource;

    @Autowired
    public Sid sid;

    /**
     * 使用FastDFS上传文件
     */
    @Override
    public String uploadFastDFS(MultipartFile file, String fileExtName) throws Exception {
        InputStream inputStream = file.getInputStream();
        StorePath storePath = this.fastFileStorageClient.uploadFile(inputStream, file.getSize(), fileExtName, null);
        inputStream.close();
        return storePath.getFullPath();
    }

    @Override
    public String uploadOSS(MultipartFile file, String userId, String fileExtName) throws Exception {
        // Endpoint以杭州为例, 其它Region请按实际情况填写, 直接查看自己的云存储信息即可
        String endpoint = fileResource.getEndpoint();
        // 阿里云AccessKey
        String accessKeyId = aliyunResource.getAccessKeyID();
        // 阿里云accessKeySecret
        String accessKeySecret = aliyunResource.getAccessKeySecret();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 组装存储再oss上的文件路径, 例如: images/abc/10010/jkdsahu5412456.png
        String myObjectName = fileResource.getObjectName() + "/" + userId + "/" + sid.nextShort() + "." + fileExtName;

        // 上传文件信息
        InputStream inputStream = file.getInputStream();
        ossClient.putObject(fileResource.getBucketName(), myObjectName, inputStream);
        ossClient.shutdown();

        // 将文件路径返回到前端, 后续可以保存再自己的数据库
        return myObjectName;
    }
}
